package com.settlement.system.service.impl;

import com.settlement.system.common.util.DateUtils;
import com.settlement.system.config.WxPayConfig;
import com.settlement.system.model.entity.SysLazyToolUser;
import com.settlement.system.model.entity.SysPayOrder;
import com.settlement.system.service.SysLazyToolUserService;
import com.settlement.system.service.SysPayOrderService;
import com.settlement.system.service.WxPayService;
import com.yungouos.pay.wxpay.WxPay;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WxPayServiceImpl implements WxPayService {

    private final SysPayOrderService sysPayOrderService;

    private final SysLazyToolUserService sysLazyToolUserService;

    @Override
    public Map<String, Object> nativePay(Long userId, String body, String money) {
        Map<String, Object> map = null;
        try {
            SysPayOrder payOrder = new SysPayOrder();
            SysLazyToolUser sysLazyToolUser = sysLazyToolUserService.getById(userId);
            payOrder.setMobile(sysLazyToolUser.getMobile());
            // 订单编号
            payOrder.setOrderNo("LU%s%s".formatted(sysLazyToolUser.getId(), DateUtils.getDateString()));
            // 付款备注
            payOrder.setBody(body);
            // 付款金额
            payOrder.setMoney(Long.parseLong(money));
            SysPayOrder order = sysPayOrderService.saveSysPayOrder(payOrder);
            if (order == null) {
                throw new Exception("订单保存失败");
            }
            map = new HashMap<>();
            // 回调地址 TODO
            String notify_url = "http://TODO/api/wxpay/callback/notify";
            String result = WxPay.nativePay(order.getOrderNo(), order.getMoney().toString(), WxPayConfig.mchId, order.getBody(), "2", null, notify_url, null, null, null, null, WxPayConfig.key);
            map.put("url", result);
            map.put("orderNo", order.getOrderNo());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
